package shawnho.ideaagent;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.net.JksOptions;
import io.vertx.ext.web.Router;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author shawnho
 */
public class AuthServer {
    public void run() {
        System.setProperty("vertx.disableFileCaching", "true");
        System.setProperty("vertx.disableFileCPResolving", "true");
        Vertx vertx = Vertx.vertx();
        HttpServer server = vertx.createHttpServer(new HttpServerOptions().setSsl(true).setKeyStoreOptions(new JksOptions().setValue(Buffer.buffer(toByteArray(AuthServer.class.getClassLoader().getResourceAsStream("authserver.jks")))).setPassword("123456")));
        Router router = Router.router(vertx);
        router.get("/q1").handler(req -> {
            HttpServerResponse response = req.response();
            response.putHeader("content-type", "text/plain;charset=UTF-8");
            response.end("8a01f3a38c0b42025f794ed89da276b6f818970d29444e02c1e9c2fa2d19c954a5744f9765effc2fe38ae5e70387e2b2484d5d65f8a358e1d75e8058092a6620ff3a0a1e92273fb5d066324b98cf4a157dbf236b0488867b7f3bb11240263c5b9662c47d46bb63ea316e542130f8641daa5df0ec0a812fe2c02f8709b5c260de");
        });
        router.get("/q2").handler(req -> {
            HttpServerResponse response = req.response();
            response.putHeader("content-type", "text/plain;charset=UTF-8");
            response.end("406eef3b90dd51111c93f0dd61c99b99425905da17dba35b086155974667c83d3a59ee6c652334a9139242847536c7d331756dbf57bdb2a7b327f2a91484507744af008b869463864e6758ab508b17198599c3164088d98e345ca9a7b1388eef42b13cf512e504d550a3c412054cc5a63cace3d47f6e63dc7a88b08395ef5301");
        });
        router.get("/q3").handler(req -> {
            HttpServerResponse response = req.response();
            response.putHeader("content-type", "text/plain;charset=UTF-8");
            response.end("73ced06155cff883f430d6411ec5743793a2e46d26fbf53004d9b763294f5de5b38ed12fb79fd08aded1ca19b3a1d67c6c80ce18e841cee8a78dc5a800c0999d2a66b77260419c10f14e8854329b9135bf95865647ee281dfe1aaba14d49efbe35e491b1df84e8f754980fb6f575fa369cb793dac9bd942242dbe7ecf390630e");
        });
        server.requestHandler(router::accept).listen(7848);
    }

    private static byte[] toByteArray(InputStream is) {
        try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            byte[] b = new byte[4096];
            int n;
            while ((n = is.read(b)) != -1) {
                output.write(b, 0, n);
            }
            return output.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
